package com.rzico.sbl.ui.report

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDeliverBinding
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.serviceId
import com.rzico.sbl.ui.report.dispatch.ReportDispatchFirstActivity
import com.rzico.sbl.ui.report.other.ReportService
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDeliverViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class ReportDeliverActivity : BaseActivity(R.layout.activity_report_deliver) {

    private val mBinding by lazy { ActivityReportDeliverBinding.bind(getRootView()) }
    private var mState = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<ReportDeliverViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initTabLayout()
        initLayout()
        initSearch()

        observe<String>("deliverModify") { updateList() }
    }

    private fun initTabLayout() {
        val index = intent.getIntExtra("index", 1)

        mBinding
            .deliverTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mState = when (it.position) {
                                0 -> "unconfirmed"
                                1 -> "dispatch"
                                2 -> "delivery"
                                3 -> "refunding"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待确认"
                    },
                    index == 1
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "配送中"
                    },
                    index == 2
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已送达"
                    },
                    index == 3
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已核销"
                    },
                    index == 4
                )
            }
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyImg.setEmptyImage(
                    resId = R.mipmap.icon_order_no,
                    dpSize = 100f
                )
                it.emptyHint.text = "暂无相关运单信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = {
                        orderCount()
                        getData(0)
                    },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_time, bean.hint + bean.time)
                            text(R.id.item_order_status, bean.status_hint)

                            clicked {
                                goToOrderDetail(
                                    "title" to "运单详情",
                                    "orderSn" to bean.orderSN,
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_type, "规格: ${bean.spec.orEmpty()}")
                            text(R.id.item_order_price, "")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_order_img_type) {
                                when (bean.methodDescr) {
                                    "promotion" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_report_v2_03)
                                    }
                                    else -> it.gone()
                                }
                            }

                            clicked {
                                goToOrderDetail(
                                    "title" to "运单详情",
                                    "orderSn" to bean.orderSN,
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_order_hope)
                            gone(R.id.item_order_layout)
                            text(R.id.item_order_count, bean.total_num)
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_phone, bean.phone)
                            text(R.id.item_order_addr, bean.address)

                            with<TextView>(R.id.item_order_pei) { tv ->
                                tv.text =
                                    "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " $it" }}"
                                tv.visibility = goneValue { bean.adminName.isEmpty() }
                            }

                            with<TextView>(R.id.item_order_btn1) {
                                it.text = bean.hint_btn1
                                it.visibility = goneValue { bean.hint_btn1.isEmpty() }

                                it.oneClick {
                                    if (bean.printStatus.isNotEmpty()
                                        && bean.printStatus != "confirmed"
                                        && bean.printStatus != "printed"
                                    ) {
                                        showToast("未打单不能送达")
                                        return@oneClick
                                    }

                                    when (serviceId) {
                                        in ReportService.SEND_CONTROL -> {
                                            getViewModel()
                                                .requestBind(
                                                    requestUrl = ReportUrl.getBaseUrl().depotIsOut,
                                                    params = arrayOf("id" to bean.orderId)
                                                )
                                                .bindLifeCycle(getLifecycleOwner())
                                                .subscribeBySuccess(
                                                    event = getViewModel(),
                                                    onSuccess = {
                                                        startActivityEx<ReportDispatchFirstActivity>(
                                                            "shipId" to bean.id,
                                                            "orderSn" to bean.orderSN,
                                                            "shippingSn" to bean.shippingSn
                                                        )
                                                    }
                                                )
                                        }
                                        else ->
                                            startActivityEx<ReportDispatchFirstActivity>(
                                                "shipId" to bean.id,
                                                "orderSn" to bean.orderSN,
                                                "shippingSn" to bean.shippingSn
                                            )
                                    }
                                }
                            }

                            with<TextView>(R.id.item_order_btn2) {
                                it.text = bean.hint_btn2
                                it.visibility = goneValue { bean.hint_btn2.isEmpty() }

                                it.oneClick { printOrder(bean.orderSN, bean.position) }
                            }

                            with<TextView>(R.id.item_order_btn3) {
                                it.text = bean.hint_btn3
                                it.visibility = goneValue { bean.hint_btn3.isEmpty() }

                                it.oneClick { revokeOrder(bean.orderSN) }
                            }

                            clicked {
                                goToOrderDetail(
                                    "title" to "运单详情",
                                    "orderSn" to bean.orderSN,
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .deliverSearch
            .apply {
                searchEdit.hint = "请输入收货人、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入收货人、电话、地址")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入收货人、电话、地址")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    /**
     * 更新自定义Tab数量
     */
    private fun orderCount() {
        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("unconfirmed"),
                            obj.optNotNull("confirmed"),
                            obj.optNotNull("completed"),
                            mBinding.deliverTab
                        )
                }
            )
    }

    /**
     * 运单配送中撤销
     */
    private fun revokeOrder(orderSN: String) {
        showHintDialog(
            title = "订单撤销",
            hint = "确定要撤回无法配送的订单吗？",
            onSure = {
                getViewModel()
                    .operateDeliver(ReportUrl.getBaseUrl().rptDeliverRoe, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("撤销成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 打印订单
     */
    private fun printOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "订单打印",
            hint = "确定要打印订单吗？",
            onSure = {
                getViewModel()
                    .operateDeliver(ReportUrl.getBaseUrl().reportPrt, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单打印成功！")

                            val item =
                                mList.find { it is OrderFooter && it.position == index } as OrderFooter
                            item.printStatus = "confirmed"
                            item.hint_btn2 = ""

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        )
    }

    /**
     * 报货运单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .deliverList(
                page = index,
                state = mState,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        orderCount()
        getData(0)
    }

}